<!-- 知识库创建类型 -->
<template>
  <el-dialog
    class="dialogAdapter"
    :destroy-on-close="true"
    @close="handleClose"
    style="border-radius: 10px"
    v-model="props.visible"
    :title="`${!type ? '创建' : '编辑'}语音模型`"
    width="30%"
  >
    <!--知识库from -->
    <el-form ref="ruleFormRef" :model="d.form" label-position="top">
      <el-form-item prop="name" label="名称" :rules="[{ required: true, message: '请输入名称' }]">
        <el-input v-model="d.form.name" autocomplete="off" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item
        prop="gender"
        label="性别"
        :rules="[
          {
            required: true,
            message: '请选择性别',
            trigger: 'change'
          }
        ]"
      >
        <el-select class="w-100" v-model="d.form.gender" placeholder="请选择性别">
          <el-option label="男" value="1" />
          <el-option label="女" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="模型"
        :rules="[
          {
            required: true,
            message: '请选择模型',
            trigger: 'change'
          }
        ]"
      >
        <el-select class="w-100" v-model="d.form.model" placeholder="请选择模型">
          <el-option label="AU" value="AU" />
          <el-option label="BARD" value="BARD" />
          <el-option label="CHAT" value="CHAT" />
        </el-select>
      </el-form-item>
      <el-form-item label="录音文件" v-if="!type && d.form.model === 'BARD'">
        <el-select @change="onSoundModeType" class="w-100" v-model="soundMode" placeholder="请选择录音方式">
          <el-option label="上传录音" value="soundMode_1" />
          <el-option label="在线录音" value="soundMode_2" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="d.form.model !== 'BARD'"
        prop="voice_name"
        label="VOICE_NAME"
        :rules="[{ required: true, message: '请输入VOICE_NAME' }]"
      >
        <el-input v-model="d.form.voice_name" autocomplete="off" placeholder="请输入VOICE_NAME" />
      </el-form-item>
      <el-form-item
        v-if="d.form.model !== 'BARD'"
        prop="voice_style"
        label="VOICE_STYLE"
        :rules="[{ required: true, message: '请输入VOICE_STYLE' }]"
      >
        <el-input v-model="d.form.voice_style" autocomplete="off" placeholder="请输入VOICE_STYLE" />
      </el-form-item>
      <!-- 上传录音 -->
      <el-upload
        v-if="!type && d.form.model === 'BARD' && soundMode === 'soundMode_1'"
        ref="uploadRef"
        :limit="1"
        class="upload-demo"
        drag
        action="#"
        :http-request="handleFileUpload"
        :before-upload="beforeUpload"
        :on-exceed="handleExceed"
        accept="audio/*"
      >
        <!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon> -->
        <img class="updataImg" :src="updata" alt="" srcset="" />
        <div class="el-upload__text">点击或拖动文件到此处上传</div>
        <div class="el-upload__text">请上传MP3格式的文件</div>
      </el-upload>
      <!-- end -->
      <Tape @callback="tapecallback" v-if="d.form.model === 'BARD' && soundMode === 'soundMode_2'" ref="tapeRef" />
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!type" type="danger" @click="submitForm(ruleFormRef)"> 创建 </el-button>
        <el-button v-else type="danger" @click="submitEditForm(ruleFormRef)"> 编辑 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { APIVoiceAdd, APIVoiceUp } from "@/api/ApiSpeechModel"
import { ElMessage, FormInstance, genFileId, UploadInstance, UploadProps, UploadRawFile } from "element-plus"
import { onMounted, reactive, ref } from "vue"
import Tape from "@/components/Tape/index.vue"

// @ts-ignore
import debounce from "@/utils/debounce"
import pubsub from "pubsub-js"
import updata from "@/assets/docs/updata.svg"
const uploadRef = ref<UploadInstance>()
const tapeRef = ref()
interface Props {
  editData?: any
  type?: string
  visible: boolean
}

const emits = defineEmits(["editDpData", "close"])
const props = defineProps<Props>()
const ruleFormRef = ref()
const soundMode = ref("soundMode_1")
// 云模型from
const d = reactive({
  form: {
    name: "",
    voice_name: "",
    voice_style: "",
    gender: "", //1男0女
    model: "", //模型：AU，BARD，CHAT
    voice_file: "" //录音文件
  }
})

// 清空数据
const dfData = {
  name: "",
  voice_name: "",
  voice_style: "",
  gender: "",
  model: "",
  voice_file: ""
}

onMounted(() => {
  if (props.editData && props.type) {
    d.form = props.editData
  }
})

// 创建提交
const submitForm = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const { code } = await APIVoiceAdd(d.form)
      if (code === 200) {
        pubsub.publish("UPDATESPEECHMODWLLIST")
        handleClose()
        ElMessage({
          type: "success",
          message: "添加成功"
        })
        d.form = dfData
      }
    } else {
      console.log("error submit!")

      return false
    }
  })
}, 300)

const handleClose = () => {
  emits("close")
}
// 编辑提交
const submitEditForm = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log(valid, d.form, "submit!")
      const { code, data } = await APIVoiceUp(d.form)
      if (code === 200) {
        emits("editDpData", { ...d.form, ...data })
      }
    } else {
      console.log("error submit!")
      return false
    }
  })
}, 300)

// 处理文件上传暂存
const handleFileUpload = (file: any) => {
  d.form.voice_file = file.file
}

// 格式检查
const beforeUpload = (file: any) => {
  const testmsg = file.name.substring(file.name.lastIndexOf(".") + 1)
  console.log(testmsg)
  const testmsgArr = ["mp3"]
  const extension = testmsgArr.includes(testmsg)
  if (!extension) {
    ElMessage({
      type: "info",
      message: "上传错误"
    })
  }
  return extension
}

// 选中替换
const handleExceed: UploadProps["onExceed"] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

// 切换录音先打开录音权限
const onSoundModeType = (e: string) => {
  if (e === "soundMode_2") {
    setTimeout(() => {
      console.log(tapeRef.value)

      // tapeRef.value && tapeRef.value.recOpen()
    }, 10)
  }
}
// 录音结束回调
const tapecallback = (blob: any) => {
  if (blob) {
    d.form.voice_file = blob
    console.log("录音结束回调", blob)
  } else {
    console.log("录音文件不存在")
  }
}
</script>

<style lang="scss" scoped></style>
